import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.ArrayList;

public class FileConverter {
    private final Path filePath;
    private byte[] fileContent;

    public FileConverter(String filePath) throws IOException {
        this.filePath = Paths.get(filePath);
        validateFile();
        readFileContent();
    }

    private void validateFile() throws IOException {
        if (!Files.exists(filePath)) {
            throw new FileNotFoundException("文件不存在: " + filePath);
        }
        if (!Files.isRegularFile(filePath)) {
            throw new IOException("路径不是文件: " + filePath);
        }
        if (!Files.isReadable(filePath)) {
            throw new IOException("没有读取权限: " + filePath);
        }
    }

    private void readFileContent() throws IOException {
        fileContent = Files.readAllBytes(filePath);
    }

    public String convertToBinary() {
        StringBuilder binaryBuilder = new StringBuilder();
        for (byte b : fileContent) {
            // 将每个字节转换为8位二进制字符串，不足补0
            binaryBuilder.append(String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0'));
        }
        return binaryBuilder.toString();
    }

    public String convertToHex() {
        StringBuilder hexBuilder = new StringBuilder();
        for (byte b : fileContent) {
            // 将每个字节转换为2位十六进制字符串，大写
            hexBuilder.append(String.format("%02X", b));
        }
        return hexBuilder.toString();
    }

    public String saveConverted(String outputPath, String formatType) throws IOException {
        String content;
        switch (formatType.toLowerCase()) {
            case "binary":
                content = convertToBinary();
                break;
            case "hex":
                content = convertToHex();
                break;
            default:
                throw new IllegalArgumentException("不支持的格式类型，可选 'binary' 或 'hex'");
        }

        // 确保输出目录存在
        Path outputFilePath = Paths.get(outputPath);
        if (outputFilePath.getParent() != null) {
            Files.createDirectories(outputFilePath.getParent());
        }

        // 写入文件
        Files.write(outputFilePath, content.getBytes(StandardCharsets.UTF_8));
        return outputPath;
    }

    public List<String> splitHexInto512ByteChunks(String hexString) {
        List<String> chunks = new ArrayList<>();
        int chunkSize = 1024; // 512字节 = 1024个十六进制字符
        int length = hexString.length();
        
        for (int i = 0; i < length; i += chunkSize) {
            int endIndex = Math.min(i + chunkSize, length);
            String chunk = hexString.substring(i, endIndex);
            
            // 如果是最后一个块且长度不足，补零至512字节
            if (endIndex == length && chunk.length() < chunkSize) {
                int paddingLength = chunkSize - chunk.length();
                StringBuilder paddedChunk = new StringBuilder(chunk);
                for (int j = 0; j < paddingLength; j++) {
                    paddedChunk.append('0');
                }
                chunk = paddedChunk.toString();
            }
            
            chunks.add(chunk);
        }
        return chunks;
    }

    public static void main(String[] args) {
        try {
            // 示例用法
            FileConverter converter = new FileConverter("C:\\Users\\wm\\Desktop\\连连支付参数.txt");
            System.out.println("二进制长度: " + converter.convertToBinary().length());
            String hexString = converter.convertToHex();
            List<String> hexChunks = converter.splitHexInto512ByteChunks(hexString);
            System.out.println("十六进制内容已分割为 " + hexChunks.size() + " 个512字节块");
            System.out.println("第一个块内容: "  + hexChunks.get(0));
            System.out.println("十六进制内容: " + (hexString.length() > 1000 ? hexString.substring(0, 1000) + "...[截断显示，共" + hexString.length() + "字符]" : hexString));
            converter.saveConverted("C:\\Users\\wm\\Desktop\\output.bin", "binary");
            converter.saveConverted("C:\\Users\\wm\\Desktop\\output.hex", "hex");
            System.out.println("转换完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}